package com.yq.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yq.reggie.dto.DishDto;
import com.yq.reggie.dto.SetmealDto;
import com.yq.reggie.mapper.SetmealMapper;
import com.yq.reggie.pojo.Setmeal;
import com.yq.reggie.pojo.SetmealDish;
import com.yq.reggie.service.SetmealDishService;
import com.yq.reggie.service.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    @Autowired
    private SetmealDishService setmealDishService;
    /**
     * 添加套餐和套餐菜品
     * @param
     */
    @Override
    public void addWithSetmealDish(SetmealDto setmealDto) {
        //对象拷贝
        Setmeal setmeal = new Setmeal();
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        BeanUtils.copyProperties(setmealDto,setmeal);
        //添加套餐
        this.save(setmeal);
        //添加套餐菜品
        setmealDishes.stream().map((item)->{
            item.setSetmealId(setmeal.getId());
            return item;
        }).collect(Collectors.toList());
        setmealDishService.saveBatch(setmealDishes);
    }

    /**
     * 修改套餐：页面回显
     * @param id
     * @return
     */
    @Override
    public SetmealDto modify_displayWithSetmealDish(Long id) {
        //查询套餐
        Setmeal setmeal = this.getById(id);
        //查询套餐菜品
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getSetmealId,id);
        List<SetmealDish> list = setmealDishService.list(queryWrapper);
        //对象拷贝
        SetmealDto setmealDto = new SetmealDto();
        BeanUtils.copyProperties(setmeal,setmealDto);
        setmealDto.setSetmealDishes(list);
        return setmealDto;
    }

    /**
     * 修改套餐
     * @param setmealDto
     */
    @Override
    public void modifyWithSetmealDish(SetmealDto setmealDto) {
        Setmeal setmeal = new Setmeal();
        List<SetmealDish> list = setmealDto.getSetmealDishes();
        BeanUtils.copyProperties(setmealDto,setmeal);
        list.stream().map((item)->{
            item.setSetmealId(setmeal.getId());
            return item;
        }).collect(Collectors.toList());
        //修改套餐
        this.updateById(setmeal);
        //修改套餐菜品
            //清理当前套餐菜品
            LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SetmealDish::getSetmealId,setmeal.getId());
            setmealDishService.remove(queryWrapper);
        setmealDishService.saveBatch(list);
    }
}
